package Demo19;

public class Demo19 {

    public static Object locker = new Object();

    public static volatile int num = 10;

    public static volatile int count = 1;


    public static void main(String[] args) throws InterruptedException {

        //打印A
        Thread t1 = new Thread(() -> {

                while(true) {
                    synchronized (locker) {
                        while(count != 1) {
                            try {
                                locker.wait();
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                        }
                        if(num == 0) {
                            break;
                        }
                        System.out.print("A");
                        count = 2;
                        locker.notifyAll();
                    }
                }


        });

        //打印B
        Thread t2 = new Thread(() -> {

                while(true) {
                    synchronized (locker) {
                        while(count != 2) {
                            try {
                                locker.wait();
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                        }
                        if(num == 0) {
                            break;
                        }
                        System.out.print("B");
                        count = 3;
                        locker.notifyAll();
                    }
                }


        });

        //打印C
        Thread t3 = new Thread(() -> {

                while(num != 0) {
                    synchronized (locker) {
                        while(count != 3) {
                            try {
                                locker.wait();
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                        }

                        System.out.print("C");
                        System.out.println();
                        count = 1;
                        num--;
                        locker.notifyAll();

                    }
                }

        });

        t1.start();
        t2.start();
        t3.start();

        t1.join();
        t2.join();
        t3.join();

    }
}



